from celery import shared_task
from .models import Host, HostStatistics
from django.utils import timezone
from datetime import timedelta


@shared_task
def update_host_statistics():
    today = timezone.now().date()

    # 按城市和机房统计主机数量
    cities = Host.objects.values('data_center__city').distinct()

    for city in cities:
        city_instance = city['data_center__city']
        data_centers = Host.objects.filter(data_center__city=city_instance)

        for data_center in data_centers:
            host_count = data_centers.filter(data_center=data_center).count()

            # 更新 HostStatistics 表
            HostStatistics.objects.update_or_create(
                city=city_instance,
                data_center=data_center.data_center,
                date=today,
                defaults={'host_count': host_count}
            )
